package com.util.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;

import java.util.List;

/**
 * @Description: 表头
 * 背景色、字体、自动行高
 * @Author: hechaobo
 * @Date: 2024/7/31
 **/
public class MyHeadHandler implements RowWriteHandler,CellWriteHandler {
    WriteFont writeFont;
    byte[] rgb = {(byte) 201, (byte) 239, (byte) 167};
    XSSFColor color = new XSSFColor(rgb, null);
    public MyHeadHandler(){
        writeFont=new WriteFont();
        writeFont.setBold(true);
        writeFont.setFontHeightInPoints((short) 10);
    }
    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        if(isHead){
            //自动行高
            row.setHeightInPoints(-1);
        }
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if(isHead){
            WriteCellData<?> writeCellData = cellDataList.get(0);
            WriteCellStyle orCreateStyle = writeCellData.getOrCreateStyle();
            orCreateStyle.setFillForegroundColor(null);
            writeCellData.setOriginCellStyle(getCellStyle(cell));
            orCreateStyle.setWriteFont(writeFont);
        }
    }
    CellStyle cellStyle;
    public CellStyle getCellStyle(Cell cell){
        if(cellStyle == null){
            cellStyle=cell.getSheet().getWorkbook().createCellStyle();
            ((XSSFCellStyle)cellStyle).setFillForegroundColor(color);
        }
        return cellStyle;
    }
}
